<template>
  <div>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" show-icon type="warning">
      </el-alert>

      <el-row class="cat_opt">
        <span>选择商品分类：</span>
        <el-cascader v-model="cateList" :options="options"
                     :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children'}"
                     @change="handleChange"></el-cascader>
      </el-row>

      <el-tabs v-model="tabActiveName" v-loading="loading">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" size="mini" @click="addDialogVisible=true">添加参数
          </el-button>
          <el-table :data="tableData">
            <el-table-column type="expand">
              <template v-slot="scopeInfo">
                <el-tag closable type="primary" v-for="(item, i) in scopeInfo.row.attr_vals" :key="item"
                        @close="removeTag(i, scopeInfo.row)">{{item}}
                </el-tag>
                <el-input v-if="newTagVisible" v-model="tagValue" ref="saveTagInput" size="small" class="input-new-tag"
                          @keyup.enter.native="handleTag(scopeInfo.row)" @blur="handleTag(scopeInfo.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showAddTag">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scopeInfo">
                <el-button type="primary" size="mini">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteParams(scopeInfo.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" size="mini" @click="addDialogVisible=true">添加属性
          </el-button>
          <el-table :data="tableData">
            <el-table-column type="expand">
              <template v-slot="scopeInfo">
                <el-tag closable type="primary" v-for="(item, i) in scopeInfo.row.attr_vals" :key="item"
                        @close="removeTag(i, scopeInfo.row)">{{item}}
                </el-tag>
                <el-input v-if="newTagVisible" v-model="tagValue" ref="saveTagInput" size="small" class="input-new-tag"
                          @keyup.enter.native="handleTag(scopeInfo.row)" @blur="handleTag(scopeInfo.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showAddTag">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scopeInfo">
                <el-button type="primary" size="mini">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteParams(scopeInfo.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @closed="handleClose">
      <el-form :model="addForm" label-width="100px" :rules="addFromRules" ref="addFromRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiGetCategories,
  apiGetCateAttributes,
  apiAddCateAttributes,
  apiEditCateAttributes,
  apiDeleteCateAttributes
} from '@/api/index.js'

export default {
  name: 'Params',
  created () {
    this.getCateList()
  },
  data () {
    return {
      // 选中的商品分类
      cateList: [],
      // 所有 商品分类数据
      options: [],
      // 当前 tab 页
      tabActiveName: 'many',
      tableData: [],
      loading: false,
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFromRules: {
        attr_name: [
          { required: true, message: '请输入动态参数', trigger: 'blur' }
        ]
      },
      // 标签
      newTagVisible: false,
      tagValue: ''
    }
  },
  methods: {
    // 获取 category 信息
    async getCateList () {
      const { data: res } = await apiGetCategories()
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.options = res.data
    },
    // 获取 动态参数/静态属性
    async getCateAttr () {
      if (this.cateList.length !== 3) {
        return false
      }
      this.loading = true
      let id = this.cateList[this.cateList.length - 1]
      let type = this.tabActiveName
      const { data: res } = await apiGetCateAttributes(id, { sel: type })
      this.loading = false
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status + ' ' + res.meta.msg
        )
      }
      res.data.forEach(item => {
        item.attr_vals = (item.attr_vals === '' ? [] : item.attr_vals.split(' '))
      })
      this.tableData = res.data
    },
    // 商品分类被选择
    handleChange () {
      this.getCateAttr()
    },
    // 添加 参数/属性 dialog关闭回调
    handleClose () {
      this.$refs.addFromRef.resetFields()
    },
    // 添加 参数/属性
    addParams () {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return false
        let id = this.cateList[this.cateList.length - 1]
        const { data: res } = await apiAddCateAttributes(id, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.tabActiveName
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.status + ' ' + res.meta.msg)
        }
        this.$message.success('操作成功')
        this.addDialogVisible = false
        this.getCateAttr()
      })
    },
    // 移除标签
    removeTag (i, row) {
      row.attr_vals.splice(i, 1)
      this.editParams(row)
    },
    // 添加标签
    showAddTag () {
      this.newTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 添加 标签
    handleTag (row) {
      this.newTagVisible = false
      if (this.tagValue.trim().length === 0) {
        this.tagValue = ''
        return
      }
      row.attr_vals.push(this.tagValue)
      this.tagValue = ''
      this.editParams(row)
    },
    // 修改参数
    async editParams (row) {
      const { data: res } = await apiEditCateAttributes(row.cat_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: this.tabActiveName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status + ' ' + res.meta.msg)
      }
      this.$message.success('操作成功')
    },
    // 删除参数
    async deleteParams (row) {
      let result = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      console.log(result)
      if (result !== 'confirm') return

      const { data: res } = await apiDeleteCateAttributes(row.cat_id, row.attr_id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status + ' ' + res.meta.msg)
      }
      this.$message.success('操作成功')
      this.getCateAttr()
    }
    // TODO 分类参数 编辑功能
  },
  watch: {
    // 标签页切换 更新数据
    tabActiveName () {
      this.getCateAttr()
    }
  },
  computed: {
    // 按钮是否启用
    isBtnDisabled () {
      if (this.cateList.length !== 3) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.tableData = []
        return true
      }
      return false
    },
    // 动态展示 添加参数 dialog
    titleText () {
      if (this.tabActiveName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
  .el-cascader {
    width: 300px;
  }

  .cat_opt {
    margin: 15px 0;
  }

  .el-tag {
    margin: 10px;
  }

  .input-new-tag {
    width: 120px;
  }
</style>
